﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>添加班组</title>
    <link href="~/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
    <style>
        .layui-form {
            padding: 20px;
            margin-right: 30px;
        }
        .layui-form-item {
            margin-bottom: 20px;
        }
        .form-buttons {
            text-align: center;
            margin-top: 30px;
        }
        .team-number-container {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        .team-number-container .layui-input {
            flex: 1;
        }
        .auto-generate-switch {
            white-space: nowrap;
            font-size: 13px;
        }
    </style>
</head>
<body>
    <form class="layui-form" lay-filter="addTeamForm">
        @Html.AntiForgeryToken()
        <div class="layui-form-item">
            <label class="layui-form-label">班组编号</label>
            <div class="layui-input-block">
                <div class="team-number-container">
                    <input type="text" id="teamNumber" name="teamNumber" lay-verify="required" placeholder="请输入班组编号" autocomplete="off" class="layui-input">
                    <div class="auto-generate-switch">
                        <input type="checkbox" id="autoGenerate" name="autoGenerate" lay-skin="switch" lay-text="自动|手动" lay-filter="autoGenerate" title="自动生成">
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">班组名称</label>
            <div class="layui-input-block">
                <input type="text" name="teamName" lay-verify="required" placeholder="请输入班组名称" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">班组分类</label>
            <div class="layui-input-block">
                <select name="teamType" lay-verify="required" lay-search>
                    <option value="">请选择班组分类</option>
                    <option value="1">注塑</option>
                    <option value="2">机加工</option>
                    <option value="3">组装</option>
                    <option value="4">仓库</option>
                </select>
            </div>
        </div>
        <div class="form-buttons">
            <button type="submit" class="layui-btn" lay-submit lay-filter="saveTeam">保存</button>
            <button type="button" class="layui-btn layui-btn-primary" onclick="closeDialog()">取消</button>
        </div>
    </form>

    <script src="~/scripts/jquery-3.4.1.min.js"></script>
    <script src="~/scripts/layui-v2.5.6/layui/layui.js"></script>
    <script>
        layui.use(['form', 'layer'], function(){
            var form = layui.form;
            var layer = layui.layer;
            
            // 监听自动生成开关
            form.on('switch(autoGenerate)', function(data){
                var teamNumberInput = $('#teamNumber');
                if(data.elem.checked){
                    // 自动生成模式
                    teamNumberInput.prop('readonly', true).val('正在生成...').addClass('layui-disabled');
                    generateTeamNumber();
                } else {
                    // 手动输入模式
                    teamNumberInput.prop('readonly', false).val('').removeClass('layui-disabled');
                }
            });

            // 生成班组编号
            function generateTeamNumber() {
                // 先尝试主要方法，如果失败则尝试备用方法
                $.ajax({
                    url: '/TeamSet/GenerateTeamNumber',
                    type: 'GET',
                    cache: false,
                    success: function(res) {
                        console.log('生成编号响应:', res);
                        if (res && res.success) {
                            $('#teamNumber').val(res.teamNumber);
                        } else {
                            layer.msg(res && res.message ? res.message : '生成编号失败', {icon: 2});
                            $('#teamNumber').val('');
                            // 恢复手动模式
                            $('#autoGenerate').prop('checked', false);
                            $('#teamNumber').prop('readonly', false).removeClass('layui-disabled');
                            form.render('checkbox');
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('主方法失败，尝试备用方法:', error);
                        console.error('状态码:', xhr.status);
                        console.error('响应文本:', xhr.responseText);
                        // 如果主方法失败，尝试备用方法
                        tryBackupMethod();
                    }
                });
            }

            // 备用生成方法
            function tryBackupMethod() {
                $.ajax({
                    url: '/TeamSet/GenNumber',
                    type: 'GET',
                    cache: false,
                    success: function(res) {
                        console.log('备用方法响应:', res);
                        if (res && res.success) {
                            $('#teamNumber').val(res.teamNumber);
                        } else {
                            handleGenerateError('备用方法也失败了');
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('备用方法也失败:', error);
                        console.error('状态码:', xhr.status);
                        console.error('响应文本:', xhr.responseText);
                        handleGenerateError('服务器响应错误 ' + xhr.status);
                    }
                });
            }

            // 处理生成错误
            function handleGenerateError(message) {
                layer.msg('生成编号失败：' + message, {icon: 2});
                $('#teamNumber').val('');
                // 恢复手动模式
                $('#autoGenerate').prop('checked', false);
                $('#teamNumber').prop('readonly', false).removeClass('layui-disabled');
                form.render('checkbox');
            }
            
            // 监听表单提交
            form.on('submit(saveTeam)', function(data){
                var formData = data.field;
                
                // 表单验证
                if (!formData.teamNumber) {
                    layer.msg('请输入班组编号', {icon: 2});
                    return false;
                }
                if (!formData.teamName) {
                    layer.msg('请输入班组名称', {icon: 2});
                    return false;
                }
                if (!formData.teamType) {
                    layer.msg('请选择班组分类', {icon: 2});
                    return false;
                }

                // 获取防伪令牌
                var token = $('input[name="__RequestVerificationToken"]').val();

                // 发送保存请求
                $.ajax({
                    url: '/TeamSet/SaveTeam',
                    type: 'POST',
                    contentType: 'application/json',
                    headers: {
                        'RequestVerificationToken': token
                    },
                    data: JSON.stringify({
                        teamNumber: formData.teamNumber,
                        teamName: formData.teamName,
                        teamType: formData.teamType
                    }),
                    success: function(res) {
                        if (res.success) {
                            layer.msg('保存成功', {icon: 1, time: 1000}, function(){
                                // 刷新父页面的表格
                                if (parent.layui && parent.layui.table) {
                                    parent.layui.table.reload('teamTable');
                                }
                                // 或者调用父页面的刷新方法
                                if (parent.refreshTeamSetData) {
                                    parent.refreshTeamSetData();
                                }
                                // 关闭弹窗
                                closeDialog();
                            });
                        } else {
                            layer.msg(res.message || '保存失败', {icon: 2});
                        }
                    },
                    error: function(xhr) {
                        layer.msg('服务器错误：' + (xhr.responseText || '请稍后重试'), {icon: 2});
                    }
                });
                
                return false; // 阻止表单默认提交
            });
        });

        // 关闭弹窗
        function closeDialog() {
            var index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
        }
    </script>
</body>
</html>

